
#import "RNThumbnail.h"
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVAsset.h>
#import <UIKit/UIKit.h>

@implementation RNThumbnail

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}
RCT_EXPORT_MODULE()

- (NSString *)saveThumbnail:(NSString *)outFilePath imageRef:(CGImageRef *)imageRef
{
    UIImage *thumbnail = [UIImage imageWithCGImage:*imageRef];
    
    NSData *data = UIImageJPEGRepresentation(thumbnail, 0.8);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *fullPath = [outFilePath stringByAppendingPathComponent: [NSString stringWithFormat:@"thumb-%@.jpg", [[NSProcessInfo processInfo] globallyUniqueString]]];
    
    [fileManager createFileAtPath:fullPath contents:data attributes:nil];
    
    return fullPath;
}

RCT_EXPORT_METHOD(get:(NSString *)filepath outFilePath:(NSString *)outFilePath seconds:(NSNumber *)seconds
    resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
{
    @try {
        filepath = [filepath stringByReplacingOccurrencesOfString:@"file://" withString:@""];
        NSURL *vidURL = [NSURL fileURLWithPath:filepath];
        
        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:vidURL options:nil];
        AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
        generator.appliesPreferredTrackTransform = YES;
        generator.requestedTimeToleranceBefore = kCMTimeZero;
        generator.requestedTimeToleranceAfter = kCMTimeZero;
        
        CMTime thumbTime = CMTimeMake([seconds floatValue] * 1000, 1000);
        
        AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef imageRef, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) {
            if (result == AVAssetImageGeneratorSucceeded) {
                NSString *fullPath = [self saveThumbnail:outFilePath imageRef:&imageRef];

                resolve(@{ @"path" : fullPath });
            } else {
                reject(@"couldn't generate thumbnail", nil, error);
            }
        };

        [generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];
    } @catch(NSException *e) {
        reject(e.reason, nil, nil);
    }
}

@end
